<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 积分专区
 */
class Collaborate extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private function getUserId(Request $request)
    {
        $accessToken = $request->header("accessToken");
        $redis = new Redis();
        $content = $redis->get($accessToken);
        if (!isset($content['user_id'])) {
            return $this->error("登录已失效");
        }
        $redis->set($accessToken, $content['user_id']);
        $user = Db::name("user_collaborate")->where('userId', $content['user_id'])->find();
        if(!$user['status']){
            return $this->error("您已被禁用,请联系客服");
        }
        return $content['user_id'];
    }

    public function login()
    {
        $request = Request::instance();
        $phone = $request->param("phone");
        $password = $request->param("password");
        if (!$phone || !$password || empty($password) || empty($phone)) {
            return $this->error("请输入账号密码");
        }
        $userCollaborate = DB::name('userhome t1')
            ->join('user_collaborate t2', 't1.id=t2.userId')
            ->join('collaborate t3', 't2.collaborateId=t3.id')
            ->where('t2.username', $phone)
            ->field('t1.id,t1.nickname,t1.phone,t1.avatar,t3.id as collaborateId,t3.collaborateName,t2.password,t2.status,t2.accessToken,t1.grandPrice')
            ->find();
        if (!$userCollaborate) {
            return $this->error("账号或密码错误");
        }
        if (!$userCollaborate['status']) {
            return $this->error("您已被禁用,请联系客服");
        }
        if (md5("liushuiluan$password") != $userCollaborate['password']) {
            return $this->error("账号或密码错误");
        }
        $accessToken = md5(time() . $userCollaborate['id']);
        DB::name('user_collaborate')->where('userId', $userCollaborate['id'])->update(['accessToken' => $accessToken]);
        $redis = new Redis();
        $redis->delete($userCollaborate['accessToken']);
        $redis->set($accessToken, $userCollaborate['id']);
        $userCollaborate['unInformationNum'] = DB::name('user_information')->where('userId', $userCollaborate['id'])->where('isRead', 0)->count();
        $userCollaborate['accessToken'] = $accessToken;
        $userCollaborate['userNum'] = DB::name('user_team')->where('teamUserId', $userCollaborate['id'])->where('status', 1)->count();
        unset($userCollaborate['password']);
        $this->success('登录成功', $userCollaborate, 200);
    }

    public function outlogin()
    {
        $request = Request::instance();
        $accessToken = $request->header("accessToken");
        $redis = new Redis();
        $redis->delete($accessToken);
        $this->success('登出成功');
    }

    public function priceIndex()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $priceMonth = $request->param("priceMonth");
        $month = date("Y-m");
        if (!$priceMonth || empty($priceMonth)) {
            $priceMonth = $month;
        }
        $user = Db::name("userhome")->where('id', $userId)->find();
        $priceStartTime = $priceMonth . "-01 00:00:00";
        $priceEndTime = date("Y-m-d", strtotime("-1 Day", strtotime("+1 Month", strtotime($priceMonth)))) . " 23:59:59";
        $userTeamPriceLogList = DB::name('user_team_price_log')
            ->where('userId', $user['id'])
            ->where('createTime', ">=", $priceStartTime)
            ->where('createTime', "<=", $priceEndTime)
            ->whereRaw('status != "PAST"')
            ->field('price,createTime')
            ->select();
        $num = date("t", strtotime($priceMonth));
        $list = [];
        for ($i = 0; $i < $num; $i++) {
            $day = date("Y-m-d", strtotime("+$i Day", strtotime($priceMonth)));
            $list[$i]['date'] = $day;
            $list[$i]['price'] = 0;
            unset($key);
            unset($value);
            foreach ($userTeamPriceLogList as $key => $value) {
                if (date("Y-m-d", strtotime($value['createTime'])) == $day) {
                    $list[$i]['price'] += $value['price'];
                    unset($userTeamPriceLogList[$key]);
                }
            }
        }
        $this->success("成功", $list);
    }

    public function userIndex()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $userMonth = $request->param("userMonth");
        $month = date("Y-m");
        if (!$userMonth || empty($userMonth)) {
            $userMonth = $month;
        }
        $user = Db::name("userhome")->where('id', $userId)->find();
        $userStartTime = $userMonth . "-01 00:00:00";
        $userEndTime = date("Y-m-d", strtotime("-1 Day", strtotime("+1 Month", strtotime($userMonth)))) . " 23:59:59";
        $userTeamList = DB::name('user_team')
            ->where('teamUserId', $user['id'])
            ->where('createTime', ">=", $userStartTime)
            ->where('createTime', "<=", $userEndTime)
            ->where('status', 1)
            ->field('createTime')
            ->select();
        $num = date("t", strtotime($userMonth));
        $list = [];
        for ($i = 0; $i < $num; $i++) {
            $day = date("Y-m-d", strtotime("+$i Day", strtotime($userMonth)));
            $list[$i]['date'] = $day;
            $list[$i]['userNum'] = 0;
            unset($key);
            unset($value);
            foreach ($userTeamList as $key => $value) {
                if (date("Y-m-d", strtotime($value['createTime'])) == $day) {
                    $list[$i]['userNum'] += 1;
                    unset($userTeamList[$key]);
                }
            }
        }
        $this->success("成功", $list);
    }

    public function getInformation()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $pageSize = $request->param("pageSize") ?: 10;
        $page = $request->param("page");
        $list = Db::name("user_information t1")
            ->join("information t2", "t1.informationId=t2.informationId")
            ->where('t1.userId', $userId)
            ->order('t1.isRead', 'asc')
            ->order('t1.createTime', 'desc')
            ->field("t1.userInformationId,t1.informationId,t2.informationTitle,t1.isRead,t1.createTime,t2.adminName")
            ->paginate($pageSize);
        $isRead = 1;
        if (isset($list->items()[0])) {
            $isRead = $list->items()[0]['isRead'];
        }
        $data = [];
        $data['informationList'] = $list->items();
        $data['totalNum'] = $list->total();
        $data['isRead'] = $isRead;
        $this->success("成功", $data);
    }

    public function getInformationShow()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $userInformationId = $request->param("userInformationId");
        $information = Db::name("user_information t1")
            ->join("information t2", "t1.informationId=t2.informationId")
            ->where('t1.userId', $userId)
            ->where('t1.userInformationId', $userInformationId)
            ->field("t1.userInformationId,t1.informationId,t2.informationTitle,t1.isRead,t1.createTime,t2.content,t2.adminName")
            ->find();
        Db::name("user_information")->where('userId', $userId)->where('userInformationId', $userInformationId)->update(['isRead' => 1]);
        $this->success("成功", $information);
    }

    //统计
    public function statistics()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $user = Db::name("userhome")->where('id', $userId)->find();
        $data = [];
        $day = date("Y-m-d");
        $data['userNum'] = DB::name('user_team')->where('teamUserId', $user['id'])->where('status', 1)->count();
        $data['todayUserNum'] = DB::name('user_team')->where('teamUserId', $user['id'])->where('createTime', "like", "%$day%")->where('status', 1)->count();
        $data['consumePrice'] = $user['consumePrice'];
        $data['withdrawPrice'] = $user['withdrawPrice'];
        $data['lockPrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'status' => "WAIT", 'source' => 'TEAM'])->sum('price');
        $data['grandPrice'] = $user['grandPrice'] + $data['lockPrice'];
        $data['todayPrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'source' => 'TEAM'])->whereRaw('status != "PAST"')->where('createTime', "like", "%$day%")->sum('price');
        $data['todayConsumePrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'status' => "ENTER", 'source' => 'TEAM'])->where('createTime', "like", "%$day%")->sum('price');
        $data['todayLockPrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'status' => "WAIT", 'source' => 'TEAM'])->where('createTime', "like", "%$day%")->sum('price');
        $day = date("Y-m-d", strtotime("-1 Day"));
        $data['yesterdayPrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'source' => 'TEAM'])->whereRaw('status != "PAST"')->where('createTime', "like", "%$day%")->sum('price');
        $data['yesterdayConsumePrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'status' => "ENTER", 'source' => 'TEAM'])->where('createTime', "like", "%$day%")->sum('price');
        $data['yesterdayLockPrice'] = DB::name('user_team_price_log')->where(['userId' => $user['id'], 'status' => "WAIT", 'source' => 'TEAM'])->where('createTime', "like", "%$day%")->sum('price');
        $this->success("成功", $data);
    }

    //收益明细
    public function priceLog()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $pageSize = $request->param("pageSize") ?: 10;
        $page = $request->param("page");
        $uid = $request->param("uid");
        $phone = $request->param("phone");
        $ordernum = $request->param("ordernum");
        $payStartTime = $request->param("payStartTime");
        $payEndTime = $request->param("payEndTime");
        $user = Db::name("userhome")->where('id', $userId)->find();
        $sql = Db::name("user_team_price_log t1")
            ->join("order t2", 't1.order_id=t2.id')
            ->join("userhome t3", 't2.userhome_id=t3.id');
        if (isset($uid) && !empty($uid)) {
            $sql->where('t3.id', 'like', "%$uid%");
        }
        if (isset($phone) && !empty($phone)) {
            $sql->where('t3.phone', 'like', "%$phone%");
        }
        if (isset($ordernum) && !empty($ordernum)) {
            $sql->where('t2.ordernum', 'like', "%$ordernum%");
        }
        if (isset($payStartTime) && !empty($payStartTime)) {
            $sql->where('t2.paytime', '>=', strtotime($payStartTime));
        }
        if (isset($payEndTime) && !empty($payEndTime)) {
            $sql->where('t2.paytime', '<=', strtotime($payEndTime));
        }
        $orderList = $sql->where(['t1.userId' => $user['id'], 'source' => 'TEAM'])
            ->order("t1.createTime", "desc")
            ->field('t1.userTeamPriceLogId,t3.id as uid,t3.phone,t2.ordernum,t2.payTime,t1.price,t1.status')
            ->paginate($pageSize);
        $list = $orderList->items();
        foreach ($list as $key => $value) {
            $list[$key]['phone'] = substr_replace($value['phone'], "****", 3, 4);
        }
        $data = [];
        $data['orderList'] = $list;
        $data['totalNum'] = $orderList->total();
        $this->success("成功", $data);
    }

    public function userStatistics()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $user = Db::name("userhome")->where('id', $userId)->find();
        $data = [];
        $data['userNum'] = DB::name('user_team')->where('teamUserId', $user['id'])->where('status', 1)->count();
        $data['userPTNum'] = DB::name('user_team t1')
            ->join("userhome t2", 't1.userId=t2.id')
            ->where('t1.teamUserId', $user['id'])
            ->where('t2.levelId', 1)
            ->where('status', 1)->count();
        $data['userBYNum'] = DB::name('user_team t1')
            ->join("userhome t2", 't1.userId=t2.id')
            ->where('t1.teamUserId', $user['id'])
            ->where('t2.levelId', 2)
            ->where('status', 1)->count();
        $data['userHJNum'] = DB::name('user_team t1')
            ->join("userhome t2", 't1.userId=t2.id')
            ->where('t1.teamUserId', $user['id'])
            ->where('t2.levelId', 3)
            ->where('status', 1)->count();
        $data['userBJNum'] = DB::name('user_team t1')
            ->join("userhome t2", 't1.userId=t2.id')
            ->where('t1.teamUserId', $user['id'])
            ->where('t2.levelId', 4)
            ->where('status', 1)->count();
        $data['userZSNum'] = DB::name('user_team t1')
            ->join("userhome t2", 't1.userId=t2.id')
            ->where('t1.teamUserId', $user['id'])
            ->where('t2.levelId', 5)
            ->where('status', 1)->count();
        $day = date("Y-m");
        $data['monthUserNum'] = DB::name('user_team')->where('teamUserId', $user['id'])->where('createTime', "like", "%$day%")->where('status', 1)->count();
        $day = date("Y-m-d");
        $data['dayUserNum'] = DB::name('user_team')->where('teamUserId', $user['id'])->where('createTime', "like", "%$day%")->where('status', 1)->count();
        $day = date("Y");
        $userTeamList = DB::name('user_team')
            ->where('teamUserId', $user['id'])
            ->where('createTime', "like", "%$day%")
            ->where('status', 1)
            ->field('createTime')
            ->select();
        $monthUserTeamList = $userTeamList;
        $day = date("Y-m");
        $num = date("t", strtotime($day));
        //计算日
        $list = [];
        for ($i = 0; $i < $num; $i++) {
            $day = date("Y-m-d", strtotime("+$i Day", strtotime(date("Y-m") . "-01")));
            $list[$i]['date'] = $day;
            $list[$i]['userNum'] = 0;
            unset($key);
            unset($value);
            foreach ($userTeamList as $key => $value) {
                if (date("Y-m-d", strtotime($value['createTime'])) == $day) {
                    $list[$i]['userNum'] += 1;
                    unset($userTeamList[$key]);
                }
            }
        }
        $data['dayList'] = $list;
        //计算月
        $list = [];
        for ($i = 0; $i < 12; $i++) {
            $month = date("Y-m", strtotime("+$i Month", strtotime(date("Y") . "-01")));
            $list[$i]['date'] = $month;
            $list[$i]['userNum'] = 0;
            unset($key);
            unset($value);
            foreach ($monthUserTeamList as $key => $value) {
                if (date("Y-m", strtotime($value['createTime'])) == $month) {
                    $list[$i]['userNum'] += 1;
                    unset($userTeamList[$key]);
                }
            }
        }
        $data['monthList'] = $list;
        $this->success("成功", $data);
    }

    public function order()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $pageSize = $request->param("pageSize") ?: 10;
        $uid = $request->param("uid");
        $phone = $request->param("phone");
        $payStartTime = $request->param("payStartTime");
        $payEndTime = $request->param("payEndTime");
        $ordernum = $request->param("ordernum");
        $status = $request->param("status");
        $excel = $request->param("excel");
        $shouhuoStartTime = $request->param("shouhuoStartTime");
        $shouhuoEndTime = $request->param("shouhuoEndTime");
        $user = Db::name("userhome")->where('id', $userId)->find();

        $sql = Db::name("user_team_price_log t1")
            ->join("order t2", 't1.order_id=t2.id')
            ->join("userhome t3", 't2.userhome_id=t3.id');
        if (isset($uid) && !empty($uid)) {
            $sql->where('t3.id', 'like', "%$uid%");
        }
        if (isset($phone) && !empty($phone)) {
            $sql->where('t3.phone', 'like', "%$phone%");
        }
        if (isset($ordernum) && !empty($ordernum)) {
            $sql->where('t2.ordernum', 'like', "%$ordernum%");
        }
        if (isset($status) && !empty($status)) {
            $sql->where('t2.status', $status);
        }
        if (isset($payStartTime) && !empty($payStartTime)) {
            $sql->where('t2.paytime', '>=', strtotime($payStartTime));
        }
        if (isset($payEndTime) && !empty($payEndTime)) {
            $sql->where('t2.paytime', '<=', strtotime($payEndTime));
        }
        if (isset($shouhuoStartTime) && !empty($shouhuoStartTime)) {
            $sql->where('t2.shouhuotime', '>=', strtotime($shouhuoStartTime));
        }
        if (isset($shouhuoEndTime) && !empty($shouhuoEndTime)) {
            $sql->where('t2.shouhuotime', '<=', strtotime($shouhuoEndTime));
        }
        $sql->where(['t1.userId' => $user['id'], 'source' => 'TEAM'])
            ->order("t1.createTime", "desc")
            ->field('t2.id as order_id,t3.id as uid,t3.phone,t2.ordernum,t2.status,t2.allprice,t2.paytime,t2.shouhuotime')
            ->group('t2.id');
        if ($excel) {
            $list = $sql->select();
        } else {
            $orderList = $sql->paginate($pageSize);
            $list = $orderList->items();
        }
        foreach ($list as $key => $value) {
            $list[$key]['phone'] = substr_replace($value['phone'], "****", 3, 4);
            $list[$key]['getPrice'] = 0;
            $list[$key]['priceStatus'] = "PAST";
            $orderDetailList = Db::name("user_team_price_log t1")
                ->join("orderdetail t2", 't1.order_detail_id=t2.id')
                ->where(['t1.order_id' => $value['order_id'], 'source' => 'TEAM'])
                ->field('t2.image,t2.name,t2.goods_spec_name,t2.num,t2.price,t2.is_shouhou,t1.price as getPrice,t1.status')
                ->select();
            unset($v);
            $status = "PAST";
            foreach ($orderDetailList as $v) {
                if ($v['status'] != "PAST") {
                    $list[$key]['getPrice'] += $v['getPrice'];
                    if ($status != "ENTER") {
                        $status = $v['status'];
                    }
                }
            }
            $list[$key]['priceStatus'] = $status;
            $list[$key]['goodList'] = $orderDetailList;
        }
        $data = [];
        if ($excel) {
//            $title_array = array(
//                '用户id',
//                '用户手机号',
//                '订单号',
//                '订单实付总价',
//                '订单状态',
//                '用户付款时间',
//                '用户确认收货时间',
//                '可获取利润',
//                '利润状态');
//            $status = ['0' => '已取消', '1' => '待支付', '2' => '已支付', '3' => '已发货', '4' => '待评价', '5' => '已完成', '9' => '已删除','6'=>"售后中"];
//            $priceStatus = ['ENTER' => '已入账', 'WAIT' => '待入账', 'PAST' => '已过期'];
//            unset($key);
//            unset($value);
//            foreach ($list as $key => $value) {
//                $data[$key][0] = "\t".$value['uid']."\t";
//                $data[$key][1] = "\t".$value['phone']."\t";
//                $data[$key][2] = "\t".$value['ordernum']."\t";
//                $data[$key][3] = "\t".$value['allprice']."\t";
//                $data[$key][4] = "\t".$status[$value['status']]."\t";
//                $data[$key][5] = "\t".($value['paytime'] ? date('Y-m-d H:i:s', $value['paytime']) : '')."\t";
//                $data[$key][6] = "\t".($value['shouhuotime'] ? date('Y-m-d H:i:s', $value['shouhuotime']) : '')."\t";
//                $data[$key][7] = "\t".$value['getPrice']."\t";
//                $data[$key][8] = "\t".$priceStatus[$value['priceStatus']]."\t";
//            }
//            $arr = array(
//                $title_array,
//                $data
//            );
//            // dump($arr);die;
//            if (empty($arr)) {
//                return false;
//            }
//            $export_str = implode(',', $arr[0]) . "\n";
//
//            if (!empty($arr[1])) {
//                foreach ($arr[1] as $k => $v) {
//                    // echo $v;die;
//                    // $newline = array("\r\n","\n","\r");
//                    // $v['contents'] = str_replace($newline, '', $v['contents']);
//                    $export_str .= implode(',', str_replace("\n", '', $v)) . "\n";
//                }
//            }
//            header("Content-type:application/vnd.ms-excel");
//            header("Content-Disposition:attachment;filename=" . '订单商品' . date('Y-m-d-H-i-s') . ".xlsx");
//            ob_start();
//            ob_end_clean();
//            echo "\xEF\xBB\xBF" . $export_str;//解决WPS和excel不乱码
            $this->success("成功", $list);
        }else{
            $data['orderList'] = $list;
            $data['totalNum'] = $orderList->total();
            $this->success("成功", $data);
        }
    }

    public function orderDetail()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $order_id = $request->param("order_id");
        $user = Db::name("userhome")->where('id', $userId)->find();
        $order = Db::name("user_team_price_log t1")
            ->join("order t2", 't1.order_id=t2.id')
            ->join("userhome t3", 't2.userhome_id=t3.id')
            ->where(['t1.order_id' => $order_id, 'source' => 'TEAM'])
            ->field('t2.id as order_id,t3.id as uid,t3.phone,t2.ordernum,t2.status,t2.allprice,t2.paytime,t2.paytime')
            ->group('t2.id')
            ->find();
        $orderDetailList = Db::name("user_team_price_log t1")
            ->join("orderdetail t2", 't1.order_detail_id=t2.id')
            ->where(['t1.order_id' => $order_id, 'source' => 'TEAM'])
            ->field('t2.image,t2.name,t2.goods_spec_name,t2.num,t2.price,t2.is_shouhou,t2.shuilv,t1.price as getPrice,t1.status')
            ->select();
        $order['phone'] = substr_replace($order['phone'], "****", 3, 4);
        foreach ($orderDetailList as $key => $value) {
            $orderDetailList[$key]['totalPrice'] = $value['num'] * $value['price'];
            $orderDetailList[$key]['shuilvPrice'] = ($orderDetailList[$key]['totalPrice'] * $value['shuilv']) / 100;
        }
        $order['goodList'] = $orderDetailList;
        $this->success("成功", $order);
    }

    public function getTeamUser()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $pageSize = $request->param("pageSize") ?: 10;
        $uid = $request->param("uid");
        $phone = $request->param("phone");
        $createStartTime = $request->param("createStartTime");
        $createEndTime = $request->param("createEndTime");

        $user = Db::name("userhome")->where('id', $userId)->find();
        $sql = Db::name("userhome t1")
            ->join("user_team t2", 't1.id=t2.userId')
            ->join("level t3", 't1.levelId=t3.levelId')
            ->where('t2.teamUserId', $user['id'])
            //->where('t1.id != '.$user['id'])
            ->where('t2.status', 1);
        if (isset($uid) && !empty($uid)) {
            $sql->where('t1.id', 'like', "%$uid%");
        }
        if (isset($phone) && !empty($phone)) {
            $sql->where('t1.phone', 'like', "%$phone%");
        }
        if (isset($createStartTime) && !empty($createStartTime)) {
            $sql->where('t2.createTime', '>=', strtotime($createStartTime));
        }
        if (isset($createEndTime) && !empty($createEndTime)) {
            $sql->where('t2.createTime', '<=', strtotime($createEndTime));
        }
        $userList = $sql->order("t2.createTime", 'desc')
            ->field('t1.id as uid,t1.phone,t3.levelName,t2.createTime,t1.add_integral,t1.use_integral,t1.spend')
            ->paginate($pageSize);
        $data = [];
        $data['userList'] = $userList->items();
        $data['totalNum'] = $userList->total();
        $this->success("成功", $data);
    }

    public function getTeamUserShow()
    {
        $request = Request::instance();
        $userId = $this->getUserId($request);
        $pageSize = $request->param("pageSize") ?: 10;
        $listType = $request->param("listType");
        $userId = $request->param("userId");
        $uid = $request->param("uid");
        $phone = $request->param("phone");
        $createStartTime = $request->param("createStartTime");
        $createEndTime = $request->param("createEndTime");

        $user = Db::name("userhome")->where('id', $userId)->find();
        $sql = Db::name("userhome t1")
            ->join("user_relation t2", 't1.id=t2.userId')
            ->join("level t3", 't1.levelId=t3.levelId');
        if ($listType == "indirect") {
            $userPhoneList = Db::name("user_relation")->where('inviteUserId', $user['id'])->field('userId')->select();
            $inviteUserPhoneList = [];
            foreach ($userPhoneList as $value) {
                $inviteUserPhoneList[] = $value['userId'];
            }
            $sql->whereIn('t2.inviteUserId', $inviteUserPhoneList);
            //return var_dump($inviteUserPhoneList);
        } else {
            $sql->where('t2.inviteUserId', $user['id']);
        }
        if (isset($uid) && !empty($uid)) {
            $sql->where('t1.id', 'like', "%$uid%");
        }
        if (isset($phone) && !empty($phone)) {
            $sql->where('t1.phone', 'like', "%$phone%");
        }
        if (isset($createStartTime) && !empty($createStartTime)) {
            $sql->where('t2.createTime', '>=', strtotime($createStartTime));
        }
        if (isset($createEndTime) && !empty($createEndTime)) {
            $sql->where('t2.createTime', '<=', strtotime($createEndTime));
        }
        $userList = $sql->order("t2.createTime", 'desc')
            ->field('t1.id as uid,t1.phone,t3.levelName,t2.createTime,t1.add_integral,t1.use_integral,t1.spend')
            ->paginate($pageSize);
        $data = [];
        $data['superiorsUser'] = Db::name("userhome t1")
            ->join("user_relation t2", 't1.id=t2.userId',"LEFT")
            ->join("level t3", 't1.levelId=t3.levelId')
            ->join("user_relation t4", 't1.id=t4.inviteUserId')
            ->where('t4.userId', $user['id'])
            ->field('t1.id as uid,t1.phone,t3.levelName,t1.createtime,t2.createTime,t1.add_integral,t1.use_integral,t1.spend')
            ->find();
        if(isset($data['superiorsUser'])){
            if(!isset($data['superiorsUser']['createTime'])){
                $data['superiorsUser']['createTime'] = date("Y-m-d H:i:s",$data['superiorsUser']['createtime']);
                unset($data['superiorsUser']['createtime']);
            }
        }
        $data['userList'] = $userList->items();
        $data['totalNum'] = $userList->total();
        $this->success("成功", $data);
    }
}
